import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by L.jp
 * Description:
 * User: 86189
 * Date: 2021-10-10
 * Time: 14:02
 */
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) {
          this.val = val;
      }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
}
class Node{
    TreeNode root;
    int depth;
    int pos;
    Node(TreeNode root, int depth, int pos){
        this.root = root;
        this. depth = depth;
        this.pos = pos;
    }
}
class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        Queue<Node> q = new LinkedList<Node>();
        q.offer(new Node(root, 1, 0));
        int ans = 0, curDepth = 0, curLeft = 0;
        while(!q.isEmpty()){
            Node n = q.poll();
            if(n.root != null){
                q.offer(new Node(n.root.left, n.depth + 1, n.pos * 2));
                q.offer(new Node(n.root.right, n.depth + 1, n.pos * 2 + 1));
                if(curDepth != n.depth){
                    curDepth = n.depth;
                    curLeft = n.pos;
                }
                ans = Math.max(ans, n.pos - curLeft + 1);
            }
        }
        return ans;
    }
}
